<template>
  <!-- 无UI组件，仅用于管理用户类型和路由 -->
</template>

<script setup>
import { onMounted, watch, onUnmounted } from 'vue'; // 1. 导入 onUnmounted
import { useUserStore } from '@/store/user';
//import { getCurrentPages } from '@dcloudio/uni-app'; // 引入 getCurrentPages 函数

const userStore = useUserStore();

// 商家专属页面列表
const merchantPages = [
  '/pages/merchant/dashboard',
  '/pages/merchant/orders',
  '/pages/merchant/products',
  '/pages/merchant/settings'
];

// 监听页面跳转
const handleRouteChange = () => {
  const pages = getCurrentPages();
  if (pages.length === 0) return;
  
  const currentPage = pages[pages.length - 1];
  const currentRoute = `/${currentPage.route}`;
  
  // 如果是商家页面，但当前用户不是商家
  if (merchantPages.includes(currentRoute) && !userStore.isMerchant()) {
    uni.showToast({
      title: '请先登录商家账号',
      icon: 'none'
    });
    uni.switchTab({
      url: '/pages/index/index'
    });
  }
};

// 监听用户类型变化
watch(() => userStore.userType, (newType) => {
  if (newType === 'merchant') {
    // 如果当前不在商家页面，则跳转到商家首页
    const pages = getCurrentPages();
    if (pages.length > 0) {
      const currentPage = pages[pages.length - 1];
      const currentRoute = `/${currentPage.route}`;
      
      if (!merchantPages.includes(currentRoute)) {
        uni.reLaunch({
          url: '/pages/merchant/dashboard'
        });
      }
    }
  }
});

onMounted(() => {
  // 初始化用户状态
  userStore.initUserState();
  
  // 监听页面显示事件
  uni.$on('page-show', handleRouteChange);
});

// 组件卸载时移除事件监听
onUnmounted(() => {
  uni.$off('page-show', handleRouteChange);
});
</script>